package org.elsa.fingobtb.api.controller;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.elsa.fingobtb.api.response.BaseResult;
import org.elsa.fingobtb.common.func.BtbRestfulBase;
import org.elsa.fingobtb.common.utils.ApiAuth;
import org.elsa.fingobtb.common.utils.BaseController;
import org.elsa.fingobtb.common.utils.UToken;
import org.elsa.fingobtb.entity.request.CreateOrder;
import org.elsa.fingobtb.service.CoinFitService.BuyByCoinFit;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

@RestController
@RequestMapping(value="/coinFit")
public class CoinFitApi extends BaseController {

    @Resource
    BtbRestfulBase btbRestfulBase;

    @Resource
    BuyByCoinFit buyByCoinFit;

    @ApiOperation(value="getMarkets", notes="获取市场" )
    @RequestMapping(value="/getMarkets",method= {RequestMethod.GET})
    public String getMarkets(){
        String ret = btbRestfulBase.getMarkets();
        return ret;
    }

    @ApiOperation(value="getTickers", notes="获取所有市场的股票代码" )
    @RequestMapping(value="/getTickers",method= {RequestMethod.GET})
    public Map<String, Object> getTickers(){
        String ret = btbRestfulBase.getTickers();
        return success(ret);
    }

    @ApiOperation(value="getSpecTickers", notes="Get ticker of specific market(获取特定市场的股票代码)" )
    @RequestMapping(value="/getSpecTickers",method= {RequestMethod.GET})
    public Map<String, Object> getSpecTickers(
            @ApiParam(value = "市场id",defaultValue = "hurbtc")
            @RequestParam("market")String market){
        String ret = btbRestfulBase.getSpecTickers(market);
        return success(ret);
    }

    @ApiOperation(value="getMembers", notes="Get your profile and accounts info(获取您的个人资料和帐户信息)" )
    @RequestMapping(value="/getMembers",method= {RequestMethod.GET})
    public Map<String, Object> getMembers(
            @ApiParam(value = "访问密钥",defaultValue = "") @RequestParam("access_key")String access_key,
            @ApiParam(value = "secret",defaultValue = "") @RequestParam("secret")String secret){
        Long now =(System.currentTimeMillis() / 1000)*1000;
        String payload = "GET|/api/v2/members/me.json|access_key="+access_key+"&tonce="+now;
        UToken token = ApiAuth.apiAuth(payload, access_key, secret);
        String ret = btbRestfulBase.getMembers(access_key, now, token.getSignature());
        return success(ret);
    }

    @ApiOperation(value="getDeposits", notes="Get your deposits history(获取您的存款记录)" )
    @RequestMapping(value="/getDeposits",method= {RequestMethod.GET})
    public Map<String, Object> getDeposits(
            @ApiParam(value = "访问密钥",defaultValue = "") @RequestParam("access_key")String access_key,
            @ApiParam(value = "secret",defaultValue = "") @RequestParam("secret")String secret,
            @ApiParam(value = "货币值包含btc，eth，ltc等，eos，cb，bch，ncash，hur，wecc，eosc，airdrop，rep，bat，gnt，snt，ppt，dgd，elf，aion，fun，mana") @RequestParam("currency")String currency,
            @ApiParam(value = "设置结果限制。") @RequestParam("limit")Integer limit,
            @ApiParam(value = "状态") @RequestParam("state")String state){
        Long now =(System.currentTimeMillis() / 1000)*1000;
        String payload = "GET|/api/v2/deposits.json|access_key="+access_key+"&currency="+currency+"&limit="+limit+"&state="+state+"&tonce="+now;
        UToken token = ApiAuth.apiAuth(payload, access_key, secret);
        String ret = btbRestfulBase.getDeposits(access_key, now, token.getSignature(), currency, limit, state);
        return success(ret);
    }

    @ApiOperation(value="getDeposit", notes="Get details of specific deposit(获取具体存款的详细信息)" )
    @RequestMapping(value="/getDeposit",method= {RequestMethod.GET})
    public Map<String, Object> getDeposit(
            @ApiParam(value = "访问密钥",defaultValue = "") @RequestParam("access_key")String access_key,
            @ApiParam(value = "secret",defaultValue = "") @RequestParam("secret")String secret,
            @ApiParam(value = "txid",defaultValue = "") @RequestParam("txid")String txid){
        Long now =(System.currentTimeMillis() / 1000)*1000;
        String payload = "GET|/api/v2/deposit.json|access_key="+access_key+"&tonce="+now+"&txid="+txid;
        UToken token = ApiAuth.apiAuth(payload, access_key, secret);
        String ret = btbRestfulBase.getDeposit(access_key, now, token.getSignature(), txid);
        return success(ret);
    }

    @ApiOperation(value="getDepositAddress", notes="Where to deposit. The address field could be empty when a new address is generating (e.g. for bitcoin), you should try again later in that case(在哪里存款。 当生成新地址时，地址字段可能为空（例如，对于比特币），在这种情况下您应该稍后再试)" )
    @RequestMapping(value="/getDepositAddress",method= {RequestMethod.GET})
    public Map<String, Object> getDepositAddress(
            @ApiParam(value = "访问密钥",defaultValue = "") @RequestParam("access_key")String access_key,
            @ApiParam(value = "secret",defaultValue = "") @RequestParam("secret")String secret,
            @ApiParam(value = "货币值包含btc，eth，ltc等，eos，cb，bch，ncash，hur，wecc，eosc，airdrop，rep，bat，gnt，snt，ppt，dgd，elf，aion，fun，mana") @RequestParam("currency")String currency){
        Long now =(System.currentTimeMillis() / 1000)*1000;
        String payload = "GET|/api/v2/deposit_address.json|access_key="+access_key+"&currency="+currency+"&tonce="+now;
        UToken token = ApiAuth.apiAuth(payload, access_key, secret);
        String ret = btbRestfulBase.getDepositAddress(access_key, now, token.getSignature(), currency);
        return success(ret);
    }

    @ApiOperation(value="getOrders", notes="Get your orders, results is paginated(分页获取订单)")
    @RequestMapping(value="/getOrders",method= {RequestMethod.GET})
    public Map<String, Object> getOrders(
            @ApiParam(value = "访问密钥",defaultValue = "") @RequestParam("access_key")String access_key,
            @ApiParam(value = "secret",defaultValue = "") @RequestParam("secret")String secret,
            @ApiParam(value = "市场id",defaultValue = "hurbtc") @RequestParam("market")String market,
            @ApiParam(value = "按州筛选顺序，默认为“wait”（活动订单）",defaultValue = "wait") @RequestParam("state")String state,
            @ApiParam(value = "限制退回的订单数量，默认为100。",defaultValue = "100") @RequestParam("limit")Integer limit,
            @ApiParam(value = "指定分页结果页面。") @RequestParam("page")Integer page,
            @ApiParam(value = "排序。") @RequestParam(value = "order_by", defaultValue = "asc")String order_by){
        Long now =(System.currentTimeMillis() / 1000)*1000;
        String payload = "GET|/api/v2/orders.json|access_key="+access_key+"&limit="+limit+"&market="+market+"&order_by="+order_by+"&page="+page+"&state="+state+"&tonce="+now;
        UToken token = ApiAuth.apiAuth(payload, access_key, secret);
        String ret = btbRestfulBase.getOrders(access_key, now, token.getSignature(), market, state, limit, page, order_by);
        return success(ret);
    }

   @ApiOperation(value="createOrder", notes="Create a Sell/Buy order(创建卖出/买入订单)")
    @RequestMapping(value="/createOrder",method= {RequestMethod.POST})
    public String createOrder(
            @ApiParam(value = "secret",defaultValue = "") @RequestParam("secret")String secret,
            @RequestBody CreateOrder co){
        Long now =(System.currentTimeMillis() / 1000)*1000;
        String payload = "POST|/api/v2/orders.json|access_key="+co.getAccess_key()+"&market="+co.getMarket()+"&ord_type="+co.getOrd_type()+"&price="+co.getPrice()+"&side="+co.getSide()+"&tonce="+now+"&volume="+co.getVolume();
        UToken token = ApiAuth.apiAuth(payload, co.getAccess_key(), secret);
        co.setSignature(token.getSignature());
        co.setTonce(now);
        String ret = btbRestfulBase.createOrder(co);
        return ret;
    }
/*
    @ApiOperation(value="createOrders", notes="Create multiple sell/buy orders(创建多个卖出/买入订单)")
    @RequestMapping(value="/createOrders",method= {RequestMethod.POST})
    public Map<String, Object> createOrders(
            @ApiParam(value = "secret",defaultValue = "") @RequestParam("secret")String secret,
            @RequestBody CreateOrders cos){
        Long now =(System.currentTimeMillis() / 1000)*1000;
        String payload = "POST|/api/v2/orders/multi.json|access_key="+cos.getAccess_key()+"&ord_type="+cos.getOrd_type()+"&market="+cos.getMarket()+"&price="+cos.getPrice()+"&side="+cos.getSide()+"&tonce="+now+"&volume="+cos.getVolume();
        UToken token = ApiAuth.apiAuth(payload, cos.getAccess_key(), secret);
        String ret = btbRestfulBase.createOrders(cos);
        return success(ret);
    }

    @ApiOperation(value="cancelAllMyOrders", notes="Cancel all my orders(取消我的所有订单)")
    @RequestMapping(value="/cancelAllMyOrders",method= {RequestMethod.POST})
    public Map<String, Object> cancelAllMyOrders(
            @ApiParam(value = "secret",defaultValue = "") @RequestParam("secret")String secret,
            @RequestBody CancelAllMyOrders camo){
        Long now =(System.currentTimeMillis() / 1000)*1000;
        String payload = "POST|/api/v2/orders/clear.json|access_key="+camo.getAccess_key()+"&side="+camo.getSide()+"&tonce="+now;
        UToken token = ApiAuth.apiAuth(payload, camo.getAccess_key(), secret);
        camo.setSignature(token.getSignature());
        camo.setTonce(now);
        String ret = btbRestfulBase.cancelAllMyOrders(camo);
        return success(ret);
    }*/

    @ApiOperation(value="getOrder", notes="Get information of specified order(获取指定订单信息)")
    @RequestMapping(value="/getOrder",method= {RequestMethod.GET})
    public Map<String, Object> getOrder(
            @ApiParam(value = "访问密钥",defaultValue = "") @RequestParam("access_key")String access_key,
            @ApiParam(value = "secret",defaultValue = "") @RequestParam("secret")String secret,
            @ApiParam(value = "订单id") @RequestParam("id")Integer id){
        Long now =(System.currentTimeMillis() / 1000)*1000;
        String payload = "GET|/api/v2/order.json|access_key="+access_key+"&id="+id+"&tonce="+now;
        UToken token = ApiAuth.apiAuth(payload, access_key, secret);
        String ret = btbRestfulBase.getOrder(access_key, now, token.getSignature(), id);
        return success(ret);
    }

   /* @ApiOperation(value="deleteOrder", notes="Cancel an order(取消订单)")
    @RequestMapping(value="/deleteOrder",method= {RequestMethod.POST})
    public Map<String, Object> deleteOrder(
            @ApiParam(value = "secret",defaultValue = "") @RequestParam("secret")String secret,
            @RequestBody DeleteOrder deo){
        Long now =(System.currentTimeMillis() / 1000)*1000;
        String payload = "POST|/api/v2/order/delete.json|access_key="+deo.getAccess_key()+"&id="+deo.getId()+"&tonce="+now;
        UToken token = ApiAuth.apiAuth(payload, deo.getAccess_key(), secret);
        deo.setSignature(token.getSignature());
        deo.setTonce(now);
        String ret = btbRestfulBase.deleteOrder(deo);
        return success(ret);
    }*/

    @ApiOperation(value="getOrderBook", notes="Get the order book of specified market(获取指定市场的订单)")
    @RequestMapping(value="/getOrderBook",method= {RequestMethod.GET})
    public Map<String, Object> getOrderBook(
            @ApiParam(value = "市场id",defaultValue = "hurbtc") @RequestParam("market")String market,
            @ApiParam(value = "限制退回的卖单数量。 默认为20",defaultValue = "20") @RequestParam("asks_limit") Integer asksLimit,
            @ApiParam(value = "限制退回的买单数量。 默认为20",defaultValue = "20") @RequestParam("bids_limit") Integer bidsLimit){
        String ret = btbRestfulBase.getOrderBook(market, asksLimit, bidsLimit);
        return success(ret);
    }

    @ApiOperation(value="getDepth", notes="Get depth or specified market. Both asks and bids are sorted from highest price to lowest(获得深度或指定市场。 要求和出价都从最高价格到最低价格排序)")
    @RequestMapping(value="/getDepth",method= {RequestMethod.GET})
    public String getDepth(
            @ApiParam(value = "市场id",defaultValue = "hurbtc") @RequestParam("market") String market,
            @ApiParam(value = "限制退回的价格水平。 默认为300",defaultValue = "300") @RequestParam("limit") Integer limit){
        String ret = btbRestfulBase.getDepth(market);
        return (ret);
    }

    @ApiOperation(value="getTrades", notes="Get recent trades on market, each trade is included only once. Trades are sorted in reverse creation order(获取市场上的近期交易，每笔交易仅包含一次。 交易按反向创建顺序排序)")
    @RequestMapping(value="/getTrades",method= {RequestMethod.GET})
    public Map<String, Object> getTrades(
            @ApiParam(value = "市场id",defaultValue = "hurbtc") @RequestParam("market") String market,
            @ApiParam(value = "限制退回的交易数量。 默认为50",defaultValue = "50") @RequestParam("limit") Integer limit,
            @ApiParam(value = "时间戳, 如果设置，则仅返回在时间之前执行的交易。") @RequestParam(value = "timestamp") Integer timestamp,
            @ApiParam(value = "交易ID。 如果设置，则仅返回交易后创建的交易。") @RequestParam(value = "from") Integer from,
            @ApiParam(value = "交易ID。 如果设置，则仅返回交易前创建的交易。") @RequestParam(value = "to") Integer to ){
//            @ApiParam(value = "如果设置，则返回的交易将按特定顺序排序，默认为“desc”。") @RequestParam("order_by") String order_by
        String ret = btbRestfulBase.getTrades(market, limit, timestamp, from, to);
        return success(ret);
    }

    //TODO
    @ApiOperation(value="getMyTrades", notes="Get your executed trades. Trades are sorted in reverse creation order(获得执行的交易。 交易按反向创建顺序排序)")
    @RequestMapping(value="/getMyTrades",method= {RequestMethod.GET})
    public Map<String, Object> getMyTrades(
            @ApiParam(value = "访问密钥",defaultValue = "") @RequestParam("access_key")String access_key,
            @ApiParam(value = "secret",defaultValue = "") @RequestParam("secret")String secret,
            @ApiParam(value = "市场id",defaultValue = "hurbtc") @RequestParam("market") String market,
            @ApiParam(value = "时间戳",defaultValue = "") @RequestParam("timestamp") Integer timestamp,
            @ApiParam(value = "排序方式",defaultValue = "desc") @RequestParam("order_by") String order_by,
            @ApiParam(value = "限制退回的交易数量。 默认为50",defaultValue = "50") @RequestParam("limit") Integer limit,
            @ApiParam(value = "交易ID。 如果设置，则仅返回交易后创建的交易。") @RequestParam(value = "from") Integer from,
            @ApiParam(value = "交易ID。 如果设置，则仅返回交易前创建的交易。") @RequestParam(value = "to") Integer to){
        Long now = System.currentTimeMillis();
        Long ss = now/1000;
        Integer sss = Integer.valueOf(ss.toString());
        String payload = "GET|/api/v2/trades/my.json|access_key="+access_key+"&from="+from+"&limit="+limit+"&market="+market+"&order_by="+order_by+"&timestamp="+timestamp+"&to="+to+"&tonce="+now;
        UToken token = ApiAuth.apiAuth(payload, access_key, secret);
        String ret = btbRestfulBase.getMyTrades(access_key, now, token.getSignature(), market, limit, from, to, order_by, sss);
        return success(ret);
    }

    @ApiOperation(value="getKLine", notes="Get OHLC(k line) of specific marke(获得特定市场的OHLC(K线))")
    @RequestMapping(value="/getKLine",method= {RequestMethod.GET})
    public Map<String, Object> getKLine(
            @ApiParam(value = "市场id",defaultValue = "hurbtc") @RequestParam("market") String market,
            @ApiParam(value = "限制退回的价格水平。 默认为300",defaultValue = "300") @RequestParam("limit") Integer limit,
            @ApiParam(value = "K线的时间段，默认为1.您可以选择1,5,15,30,60,120,240,360,720,1440,4320,10080") @RequestParam("period") Integer period,
            @ApiParam(value = "整数表示自Unix纪元以来经过的秒数。 如果设置，则仅返回该时间之后的k行数据。") @RequestParam("timestamp") Integer timestamp){
        String ret = btbRestfulBase.getKLine(market, limit, period, timestamp);
        return success(ret);
    }

    @ApiOperation(value="getKWithPendingTrades", notes="Get K data with pending trades, which are the trades not included in K data yet, because there's delay between trade generated and processed by K data generator(获取具有待处理交易的K数据，这些交易尚未包含在K数据中，因为K数据生成器生成和处理的交易之间存在延迟)")
    @RequestMapping(value="/getKWithPendingTrades",method={RequestMethod.GET})
    public Map<String, Object> getKWithPendingTrades(
            @ApiParam(value = "市场id",defaultValue = "hurbtc") @RequestParam("market") String market,
            @ApiParam(value = "交易id") @RequestParam("trade_id") Integer trade_id,
            @ApiParam(value = "限制返回的数据点数，默认为30", defaultValue = "30") @RequestParam("limit") Integer limit,
            @ApiParam(value = "K线的时间段，默认为1.您可以选择1,5,15,30,60,120,240,360,720,1440,4320,10080") @RequestParam("period") Integer period,
            @ApiParam(value = "整数表示自Unix纪元以来经过的秒数。 如果设置，则仅返回该时间之后的k行数据。") @RequestParam("timestamp") Integer timestamp){
        String ret = btbRestfulBase.getKWithPendingTrades(market, trade_id, limit, period, timestamp);
        return success(ret);
    }

    @ApiOperation(value="getTimeStamp", notes="getTimeStamp(获取当前时间戳)")
    @RequestMapping(value="/getTimeStamp",method= {RequestMethod.GET})
    public Map<String, Object> getTimeStamp(){
        Long now = System.currentTimeMillis()/1000*1000;
        return success(now);
    }

    @ApiOperation(value="cryptocurrencyWithdraws", notes="Get your cryptocurrency withdraws(获取加密货币提款)")
    @RequestMapping(value="/cryptocurrencyWithdraws",method= {RequestMethod.GET})
    public Map<String, Object> cryptocurrencyWithdraws(
            @ApiParam(value = "访问密钥",defaultValue = "") @RequestParam("access_key")String access_key,
            @ApiParam(value = "secret",defaultValue = "") @RequestParam("secret")String secret,
            @ApiParam(value = "货币值包含btc，eth，ltc等，eos，cb，bch，ncash，hur，wecc，eosc，airdrop，rep，bat，gnt，snt，ppt，dgd，elf，aion，fun，mana") @RequestParam("currency")String currency,
            @ApiParam(value = "设置结果限制。") @RequestParam("limit")Integer limit,
            @ApiParam(value = "state") @RequestParam("state")String state){
        Long now =(System.currentTimeMillis() / 1000)*1000;
        String payload = "GET|/api/v2/withdraws.json|access_key="+access_key+"&currency="+currency+"&limit="+limit+"&state="+state+"&tonce="+now;
        UToken token = ApiAuth.apiAuth(payload, access_key, secret);
        String ret = btbRestfulBase.cryptocurrencyWithdraws(access_key, now, token.getSignature(), currency, limit, state);
        return success(ret);
    }

    /**
     * 下单 买 限价单
     *
     * @param symbol 交易对 如wecc
     * @param price 下单价格
     * @return {"result":true,"order_id":123456}   result:true 表示成功 | order_id:􏱸􏱴ID 订单ID
     */
    @ApiOperation(value = "买进货币")
    @RequestMapping(value = "buyByConfit", method = RequestMethod.GET)
    public BaseResult buyByConfit(
            @ApiParam(value = "交易对",defaultValue = "") @RequestParam("symbol")String symbol,
            @ApiParam(value = "购买总价(RMB 整数 单位分)",defaultValue = "") @RequestParam("symbol") Integer price,
            @RequestBody CreateOrder co
            ){
        return buyByCoinFit.buyLimit(symbol, price, co);
    }

   /* @ApiOperation(value="getYourCryptocurrencyWithdraw", notes="Get your cryptocurrency withdraw.(根据id获取加密货币提款)")
    @RequestMapping(value="/getYourCryptocurrencyWithdraw",method= {RequestMethod.GET})
    public Map<String, Object> getYourCryptocurrencyWithdraw(
            @ApiParam(value = "访问密钥",defaultValue = "") @RequestParam("access_key")String access_key,
            @ApiParam(value = "secret",defaultValue = "") @RequestParam("secret")String secret,
            @ApiParam(value = "id") @RequestParam("id")String id){
        Long now =(System.currentTimeMillis() / 1000)*1000;
        String payload = "GET|/api/v2/withdraw.json|access_key="+access_key+"&id="+id+"&tonce="+now;
        UToken token = ApiAuth.apiAuth(payload, access_key, secret);
        String ret = btbRestfulBase.getYourCryptocurrencyWithdraws(access_key, now, token.getSignature(), id);
        return success(ret);
    }

    @ApiOperation(value="createWithraw", notes="Create a withdraw")
    @RequestMapping(value="/createWithraw",method= {RequestMethod.POST})
    public Map<String, Object> createWithraw(@RequestBody CreateWithraw cw,
             @ApiParam(value = "secret",defaultValue = "") @RequestParam("secret")String secret){
        Long now =(System.currentTimeMillis() / 1000)*1000;
        String payload = "POST|/api/v2/withdraw.json|access_key="+cw.getAccess_key()+"&address="+cw.getAddress()+"&currency="+cw.getCurrency()+"&fee="+cw.getFee()+"&sum="+cw.getSum()+"&tonce="+now;
        UToken token = ApiAuth.apiAuth(payload, cw.getAccess_key(), secret);
        cw.setSignature(token.getSignature());
        cw.setTonce(now);
        String ret = btbRestfulBase.CreateWithraw(cw);
        return success(ret);
    }*/
}
/*@ApiImplicitParams({
            @ApiImplicitParam(name = "access_key",value = "访问密钥",paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "tonce",value = "时间戳",paramType = "form",dataType = "Integer"),
            @ApiImplicitParam(name = "signature",value = "签名",paramType = "form",dataType = "string"),
            @ApiImplicitParam(name = "currency",value = "只接受btc",paramType = "form",dataType = "string"),
            @ApiImplicitParam(name = "sum",value = "提款金额",paramType = "form",dataType = "BigDecimal"),
            @ApiImplicitParam(name = "address",value = "加密货币地址。 现在只有比特币地址",paramType = "form",dataType = "string"),
            @ApiImplicitParam(name = "fee",value = "矿工费。 费率从0.0001到0.001 / Kb",paramType = "form",dataType = "")})*/